var paperData;
var OperaMode='' ;//A:是否模式 B:符合模式 C:得分模式 D:扣分模式 E:选项模式 F:扣分原因模式
var perDict,examInfo,ulIndex;
var opBoard,checkScore=0,nurseid,currLiId;
var titleAreaHeight=0;
var firstTop = 0
mui.init();
mui.plusReady(function () {
	baseSetup();
})
if (!mui.os.plus) {
	baseSetup()
}
function saveOperCheckData(){
	hideScoringPopover()
	var todayStr = getCurrentDeviceDay()
	var parr = perDict['userId']+'^'+perDict['releaseId']+'^'+perDict['operaId']+'^'+perDict['wardId']+'^'+todayStr+'^'+checkScore+'^S^^'; 
	var table = ''
	var SubItems = paperData['SubItems']
	for (var i = 0; i < SubItems.length;i++) {
		var oneItem = SubItems[i]
		if (table != "") {
			table += 'ˇ'
		}
		table += oneItem['SubId']+'^'+oneItem['ItemScore']+'^^'+oneItem['Remark']
	}
	var pdict = {'parr':parr,'table':table,'loginID':nurseid}
	console.log(JSON.stringify(pdict))
	var paramDict = {'method':'web.INMTeaComm:SaveOperationCheck','params':JSON.stringify(pdict),'type':'Method'}
	mui.DHCWebService(paramDict, function(result) {
		console.log(JSON.stringify(result))
		if (isNaN(parseInt(result['msg']))) {
			return;
		}
		//成功
		//更新上个页面
		var operList = plus.webview.getWebviewById('operList')
		if (operList) {
			operList.evalJS("refreshInExamItemData('"+ulIndex+"')")
		}
		mui.back()
	}, function(errorStr) {
		
	});
}
function getOperCheckData(){
	var pdict = {'UserID':perDict['userId'],'releaseId':perDict['releaseId'],'operaId':perDict['operaId']}
	//console.log(JSON.stringify(pdict))
	var paramDict = {'method':'web.INMTeaComm:GetOperationCheckApp','params':JSON.stringify(pdict),'type':'Method'}
	mui.DHCWebService(paramDict, function(result) {
		//console.log(JSON.stringify(result))
		var dataStr = result['msg'].replace(/\\"/g,'"').replace(/]"/g,"]").replace(/"\[/g,"[")
		var dataDict =JSON.parse(dataStr)
		paperData = dataDict
		if (!dataDict) {
			return;
		}
		OperaMode = dataDict['OperaMode']
		updatePaperUI(dataDict)
		if (OperaMode == 'A'||OperaMode == 'E'||OperaMode == 'F') {//是否,选项,扣分原因
			jQuery('body').append('<script src="..\/common\/js\/DHCSelectBoard.js"><\/script>')
		}else if (OperaMode == 'C'||OperaMode == 'D') {//得分/扣分
			jQuery('body').append('<script src="..\/common\/js\/DHCKeyboard.js"><\/script>')
		}else{//符合模式
			jQuery('body').append('<script src="..\/common\/js\/DHCFitBoard.js"><\/script>')
		}
		jQuery('body').append('<script src="..\/dependence\/teach\/js\/operPaper' + OperaMode + '.js"><\/script>')	
	}, function(errorStr) {
		
	});
}

function updatePaperUI(){
	var SubItems = paperData['SubItems']
	var html = '<ul class="mui-table-view">'
	for (var i = 0; i < SubItems.length;i++) {
		var oneItem = SubItems[i]
		var HasChild = oneItem['HasChild']
		var tipStr = ''
		var SubScore = oneItem['SubScore']
		if (SubScore != '') {
			tipStr = '（'+SubScore+'分）'
			if (HasChild == '0') {
				checkScore += parseFloat(SubScore)
			}
		}
		if (HasChild == '1') {
			html +='<li id="'+i+'-li" class="mui-table-view-cell title">'+oneItem['SubItem']+tipStr+'</li>'
		}else{
			var itemScore = oneItem['ItemScore']
			if (OperaMode == 'F' || OperaMode == 'B') {
				itemScore = ''
			}else if (OperaMode == 'D' && itemScore.indexOf('-') == -1) {
				itemScore = ''
			}
			html +='<li id="'+i+'-li" class="mui-table-view-cell">'+
				'<div class="mui-icon mui-icon-arrowright"></div>'+
				'<div class="oneTitle">'+oneItem['SubItem']+tipStr+'</div>'+
				'<div class="oneScore"><div class="tipText">得分：</div>'+
					//'<div class="mui-icon mui-icon-plus"></div>'+
					'<div class="scoreText">'+itemScore+'</div>'+
					// '<div class="mui-icon mui-icon-minus"></div>'+
				'</div>'+
				'<div class="oneMark"><div class="tipText">备注：</div><input readonly type="text" value="" /></div>'+
				'</li>'
			if (!SubItems[i+1]) {
				html +='</ul><div class="seperateBar"></div>'
			}else if (SubItems[i+1]['FatherId'] == '') {
				html +='</ul><div class="seperateBar"></div><ul class="mui-table-view">'
			}
		}
	}
	if (OperaMode == 'A' || OperaMode == 'B') {
		checkScore = '100%'
	}else{
		checkScore += '分'
	}
	$('#totalScore')[0].innerText = checkScore
	if (SubItems.length > 0) {
		html += '<div class="mui-btn mui-btn-primary baseBtn">提交</div>'
	}
	mui('#scroll')[0].innerHTML = html;
	mui.trigger(mui('.timerArea')[0],'tap')
	firstTop = getElementAbsPosition(mui('#0-li')[0]).top
}
function hideScoringPopover() {
	removeActive()
	mui('#remarkTextArea')[0].blur();
	if(opBoard) {
		opBoard.hideDHCKeyboard();
	}
	mui('#remarkPopo').popover('hide');
}

function keepTwoDecimalPlaces(num) {
	var numStr = num + '';
	if(numStr.indexOf('%') != -1) { //百分比
		numStr = numStr.substr(0, numStr.length - 1);
	}

	var dropIndex = numStr.indexOf('.');
	if(dropIndex != -1 && numStr.length > dropIndex + 3) {
		var third = numStr.substr(dropIndex + 3, 1);
		var thirdInt = parseInt(third);
		if(thirdInt < 5) {
			numStr = numStr.substring(0, dropIndex + 3);
			if(OperaMode == 'A' || OperaMode == 'B'){
				numStr += '%'
			}
			return numStr;
		}
		var intPatr = parseInt(numStr.substring(0, dropIndex));
		var first = parseInt(numStr.substr(dropIndex + 1, 1));
		var secondInt = parseInt(numStr.substr(dropIndex + 2, 1)) + 1;
		if(secondInt > 9) {
			first += 1;
			if(first > 9) {
				numStr = (intPatr + 1) + '.00';
			} else {
				numStr = intPatr + '.' + first + '0';
			}
		} else {
			numStr = intPatr + '.' + first + secondInt;
		}
	}
	if(isNaN(numStr)) {
		return ''
	}
	
	if(OperaMode == 'A' || OperaMode == 'B'){
		numStr += '%'
	}
	return numStr;
}

function removeActive(activeli){
	if (!activeli) {
		activeli = $('#scroll li.dhc-active')[0];
	}
	if (activeli) {
		activeli.classList.remove('dhc-active')
		activeli.classList.remove('text-active')
		activeli.classList.remove('mark-active')
	}
}

function remarkInputTapped(){
	removeActive()
	if(opBoard) {
		opBoard.hideDHCKeyboard();
	}
	var li = this.parentNode.parentNode
	li.classList.add('dhc-active')
	li.classList.add('mark-active')
	mui('#remarkPopo')[0].setAttribute('data-id',li.id)
	var index = parseInt(li.id)
	var oneData = paperData['SubItems'][index]
	mui('#remarkPopo').popover('show');
	mui('#remarkTextArea')[0].value = oneData['Remark']
}

function remarkPopoSure(){
	var remarkTextArea = mui('#remarkTextArea')[0]
	remarkTextArea.blur();
	var text = remarkTextArea.value
	var liId=mui('#remarkPopo')[0].getAttribute('data-id')
	var liDom = mui('#'+liId)[0]
	liDom.classList.remove('dhc-active')
	liDom.classList.remove('mark-active')
	var input=liDom.querySelector('input')
	input.value = text
	var index = parseInt(liId)
	paperData['SubItems'][index]['Remark']=input.value
	mui('#remarkPopo').popover('hide');
	if (currLiId && currLiId == liId) {
		mui.trigger(liDom.querySelector('.scoreText'),'tap')
	}
}

function remarkPopoCancel(){
	mui('#remarkPopo').popover('hide');
	var li = mui('#'+mui('#remarkPopo')[0].getAttribute('data-id'))[0]
	if (li) {
		li.classList.remove('dhc-active')
		li.classList.remove('mark-active')
	}
	if (currLiId && currLiId == li.id) {
		mui.trigger(li.querySelector('.scoreText'),'tap')
	}
}
function scrollToNewActiveScorLi(newLi){
	var top = getElementAbsPosition(newLi).top - firstTop;
	var scroll = mui('#scroll')[0]
	var scrollHeight = scroll.clientHeight
	if (scrollHeight-top < $('#wrapper')[0].clientHeight) {
		top = scrollHeight - $('#wrapper')[0].clientHeight
	}
	mui('#wrapper').scroll().scrollTo(0,-top,100)
}

function choseLastScoreText(){
		var activeItem = $('#scroll li.dhc-active')[0];
		if (!activeItem) {
			hideScoringPopover();
			return;
		}
		var index = parseInt(activeItem.id);
		var items = paperData['SubItems'];
		var idStr = ''
		for (var i = index-1; i >= 0;i--) {
			var itemDict = items[i];
			if (itemDict['HasChild'] != '1') {
				idStr = i+'-li';
				break;
			}
		}
		if (idStr == '') {
			mui.toast('已经是第一个了')
			return;
		}
		var newItem = $('#'+idStr)[0];
		if (newItem) {
			mui.trigger(newItem.querySelector('.scoreText'),'tap')
		}
	}
	function choseNextScoreText(){
		var activeItem = $('#scroll li.dhc-active')[0];
		if (!activeItem) {
			hideScoringPopover();
			return;
		}
		var index = parseInt(activeItem.id);
		var items = paperData['SubItems'];
		var idStr = ''
		for (var i = index+1; i < items.length;i++) {
			var itemDict = items[i];
			if (itemDict['HasChild'] != '1') {
				idStr = i+'-li';
				break;
			}
		}
		if (idStr == '') {
			mui.toast('已经是最后一个了')
			return;
		}
		var newItem = $('#'+idStr)[0];
		if (newItem) {
			mui.trigger(newItem.querySelector('.scoreText'),'tap')
		}
	}

function baseSetup(){
	mui('.mui-scroll-wrapper').scroll({
		bounce: true,
		indicators: false, //是否显示滚动条
	});
	var perInfo = app.getState()
	nurseid = perInfo['loginPerID']
	var self = plus.webview.currentWebview()
	examInfo = self.examInfo
	perDict = self.perDict
	ulIndex = self.ulIndex
	mui('#timerText')[0].setAttribute('data-init',minutesToHourMinutsSecond(examInfo['Duration']));
	mui('#titleInfo')[0].innerText = perDict['operaDesc'] + '（'+perDict['userName']+'）'
	titleAreaHeight = mui('#titleArea')[0].clientHeight
	getOperCheckData()
	
	mui('#scroll').on('tap','.baseBtn',saveOperCheckData)
	mui('#scroll').on('tap','input',remarkInputTapped)
	mui('body').on('tap','#surePat',remarkPopoSure)
	mui('body').on('tap','.remarkCancel',remarkPopoCancel)
	
	mui('body').on('tap','.timerArea',function(){
		if (this.getAttribute('class').indexOf('start') != -1) {
			this.classList.remove('start')
			clearInterval(timer)
		}else{
			this.classList.add('start')
			var timerText =  mui('#timerText')[0];
			timer = setInterval(function() {
				timerText.innerText = hourMinuteSecondPlus(timerText.innerText);
				if (mui('#timerText')[0].getAttribute('data-init') <= timerText.innerText) {
					mui.toast('时间到')
					clearInterval(timer)
				}
			}, 1000);
		}
	})
}

/*
<ul class="mui-table-view">
	<li class="mui-table-view-cell title">评估（9分）</li>
	<li class="mui-table-view-cell">
		<div class="mui-icon mui-icon-arrowright"></div>
		<div class="oneTitle">判断病人意识：呼叫病人、轻拍病人肩部</div>
		<div class="oneScore">
			<div class="tipText">得分：</div>
			<div class="mui-icon mui-icon-plus"></div>
			<div class="scoreText">3</div>
			<div class="mui-icon mui-icon-minus"></div>
		</div>
		<div class="oneMark">
			<div class="tipText">备注：</div>
			<input type="text" value="" />
		</div>
	</li>
</ul>
<div class="seperateBar"></div>



//SaveOperationCheck
parr:2^65^3^1^2022-10-18^66.67%^S^^, 
	s userId=muip(parr,"^",1)
	s releaseId=muip(parr,"^",2)
	s operaId=muip(parr,"^",3)
	s WardDR=muip(parr,"^",4)
	s CheckDate=muip(parr,"^",5)
	s:CheckDate["-" CheckDate=muizdh(CheckDate,3)
	s CheckScore=muip(parr,"^",6)
	s status=muip(parr,"^",7)
	s Remark=muip(parr,"^",8)
	s ExamId=muip(parr,"^",9)
table:3||1^√^^1ˇ3||2^×^^2ˇ3||3^√^^3,
	.s tparr=muip(table,"ˇ",i)
	.s SubId=muip(tparr,"^",1)
	.s score=muip(tparr,"^",2)
	.s ResultSubId=muip(tparr,"^",3)
	.s Remark=muip(tparr,"^",4)
loginID
*/